<?php

namespace app\common\model;

use think\Db;
use think\Model;


class Copartner extends Model
{


    // 表名
    protected $name = 'copartner';

    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'integer';

    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = false;
    protected $deleteTime = false;

    // 追加属性
    protected $append = [
        'ispay_text'
    ];


    public function getIspayList()
    {
        return ['0' => __('Ispay 0'), '1' => __('Ispay 1')];
    }


    public function getIspayTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['ispay']) ? $data['ispay'] : '');
        $list = $this->getIspayList();
        return isset($list[$value]) ? $list[$value] : '';
    }



    /**
     * Account:合伙人分佣
     * User: Ixiangang
     * Date: 2025/2/17
     * Time: 17:11
     * $user_id 上级合伙人ID
     */
    public static function money($money, $user_id, $order_id, $memo, $withdraw_id = 0)
    {

        # 查询合伙人是否存在
        $user = User::where('id', $user_id)->find();
        if (empty($user)) return false;
        $order = '';
        if ($order_id != 0) {
            # 订单信息
            $order = Order::where('id', $order_id)->find();
            if (empty($order)) return false;
        }
        Db::startTrans();
        try {
            $copartner = self::where(['user_id' => $user_id])->find();

            if ($copartner && $money != 0) {
                $before = $copartner->money;
                $after = function_exists('bcadd') ? bcadd($copartner->money, $money, 2) : $copartner->money + $money;
                $copartner->save(['money' => $after]);
                //写入日志
                $data1 = [
                    'copartner_id' => $copartner->id,
                    'user_id' => $user->id,
                    'money' => $money,
                    'before' => $before,
                    'after' => $after,
                    'withdraw_id' => $withdraw_id,
                    'memo' => $memo
                ];
                $data2 = [];
                if (!empty($order)) {
                    $data2 = [
                        'junior_user_id' => $order->user_id, //下级ID
                        'order_id' => $order->id,
                        'order_amount' => $order->pay_price,
                    ];
                }
                $params = array_merge($data1, $data2);
                CopartnerMoneyLog::create($params);
            }
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
        }
    }

}
